package com.motong.gongdan.config.mongo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.motong.gongdan.entity.DatabaseList;
import com.motong.gongdan.service.DatabaseListService;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author:fff
 * @time:2022/7/13
 */
@Component
public class MongoContext {
    @Resource
    DatabaseListService databaseListService;

    private static final Map<String, MongoDatabaseFactory> MONGO_CLIENT_DB_FACTORY_MAP = new HashMap<>();
    private static final ThreadLocal<MongoDatabaseFactory> MONGO_DB_FACTORY_THREAD_LOCAL = new ThreadLocal<>();

    @PostConstruct
    public void afterPropertiesSet() {
        List<DatabaseList> databaseListList = databaseListService.list(new QueryWrapper<DatabaseList>().isNotNull("mongo_url"));
        if(!CollectionUtils.isEmpty(databaseListList)){
            databaseListList.forEach(d->{
                MONGO_CLIENT_DB_FACTORY_MAP.put(d.getMongoDatabase(), new SimpleMongoClientDatabaseFactory(d.getMongoUrl()));
            });
        }
    }

    @Bean(name = "mongoTemplate")
    public DynamicMongoTemplate dynamicMongoTemplate() {
        Iterator<MongoDatabaseFactory> iterator = MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
        return new DynamicMongoTemplate(iterator.next());
    }

    @Bean(name = "mongoDbFactory")
    public MongoDatabaseFactory mongoDbFactory() {
        Iterator<MongoDatabaseFactory> iterator = MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
        return iterator.next();
    }

    public static void setMongoDbFactory(String name) {
        MONGO_DB_FACTORY_THREAD_LOCAL.set(MONGO_CLIENT_DB_FACTORY_MAP.get(name));
    }

    public static MongoDatabaseFactory getMongoDbFactory() {
        return MONGO_DB_FACTORY_THREAD_LOCAL.get();
    }


    public static void removeMongoDbFactory(){
        MONGO_DB_FACTORY_THREAD_LOCAL.remove();
    }

}
